<template>
  <el-form
      class="el-login-form"
      status-icon
      ref="loginForm"
      :label-position="top"
      label-width="auto"
      :model="loginFormData"
      :rules="loginFormRules"

  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="loginFormData.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="loginFormData.password" />
    </el-form-item>
    <el-form-item >
      <el-button type="primary" @click="loginFormSubmit">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>


import {reactive} from "vue";
import {ref} from "vue";
import {login} from "../../apis/user";
import {menu} from "../../apis/auth";
import request from "../../utils/request";

//登录表单的数据字段
const loginFormData = reactive({
  username:"",
  password:""
})
//登陆表单的验证规则
const loginFormRules = reactive({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名长度为5-10之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码能为空', trigger: 'blur' },
  ],

})
//登陆表单的引用对象，用于调用当前表单对象的各种方法
const loginForm = ref(null);
//async
const loginFormSubmit =  () => {
  if (!loginForm) return;
  // await
  loginForm.value.validate((valid, fields) => {
    //表单验证是否成功
    if (valid) {
      login(loginFormData).then((res)=> {
         console.log(res)
        //存储token到本地缓存
        sessionStorage.setItem("Authentication",res.data)
        //获取菜单列表
        menu().then((result) =>{
          //存储菜单列表到缓存
          sessionStorage.setItem('menu',JSON.stringify(result.data))
          console.log(JSON.parse(sessionStorage.getItem('menu')))
        })
        // console.log(menu())

      })
    } else {
      console.log('error submit!', fields)
    }
  })
}



// const loginForm = ref(null); // 初始化为null，假设在模板中会绑定到实际的表单元素
//
// const loginFormSubmit = async () => { // 移除参数，避免与外部变量冲突
//   if (!loginForm.value) return; // 使用 .value 来访问ref的实际值
//   try {
//     const { valid, fields } = await loginForm.value.validate(); // 假设validate返回一个Promise，直接解构赋值
//     if (valid) {
//       console.log('submit!');
//     } else {
//       console.log('error submit!', fields);
//     }
//   } catch (error) {
//     // 处理validate调用时可能抛出的异常
//     console.error('Validation failed:', error);
//   }
// }
</script>

<style scoped>
.el-login-form{
  padding: 50px;
  width: 400px;
  top: 50%;
 left: 50%;
  transform: translate(-50%,-50%);
  position: fixed;
  box-shadow: 0 0 10px 0 rgba(0,0,0,0.1);
}
</style>